package org.example.filter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.List;

/**
 * @Auther:Liu
 * @Testname:IsLoginSecurityFilter
 * @Date:2025/9/17 11:23
 */
@Component
@Slf4j
public class IsLoginSecurityFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        log.info("验证用户是否登录了");
        String token = request.getHeader("token");
        log.info("token: {}", token);
        if (token != null) {
            log.info("用户在线");
            //下放令牌
            List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("manager02", "manager03", "ROLE_role02");
            UsernamePasswordAuthenticationToken upat = new UsernamePasswordAuthenticationToken("aa", token, authorities);
            SecurityContextHolder.getContext().setAuthentication(upat);
        }
        //放行
        filterChain.doFilter(request, response);
    }
}
